using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace LiveStock.dataAccess
{
    /// <summary>
    /// Manages DB Connections
    /// </summary>
    class DBManager
    {
        private DBManager() { }


        public static SqlConnection GetConnection()
        {
            SqlConnection conn = new SqlConnection(Properties.Settings.Default.LiveStockConnectionString);
            return conn;
        }

        public static SqlCommand GetCommand(string commandName)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandText = commandName;
            cmd.Connection = GetConnection();
            return cmd;
        }

        public static Object ExecuteScalar(SqlCommand cmd)
        {
            Object obj;
            using (SqlConnection conn = cmd.Connection)
            {
                if (conn.State != ConnectionState.Open) conn.Open();
                obj = cmd.ExecuteScalar();
            }
            return obj;
        }

        public static SqlDataReader ExecuteReader(SqlCommand cmd)
        {
            SqlDataReader dr;
            using (SqlConnection conn = cmd.Connection)
            {
                if (conn.State != ConnectionState.Open) conn.Open();
                dr = cmd.ExecuteReader();
            }
            return dr;
        }

        public static int ExecuteNonQuery(SqlCommand cmd)
        {
            using (SqlConnection conn = cmd.Connection)
            {
                if (conn.State != ConnectionState.Open) conn.Open();
                return cmd.ExecuteNonQuery();
            }
        }

        public static void FillDataTable(DataTable dt, SqlCommand cmd)
        {
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            dap.Fill(dt);
            //close connection explicitly in case it was open before
            cmd.Connection.Close();
        }
    }
}
